package com.mengtian_tech.smart_lab.controller.console.demo;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.codec.Base64;
import com.mengtian_tech.smart_lab.entity.ApplyState;
import com.mengtian_tech.smart_lab.entity.ServiceType;
import com.mengtian_tech.smart_lab.entity.apply.ApplyForm;
import com.mengtian_tech.smart_lab.entity.cms.Attach;
import com.mengtian_tech.smart_lab.service.cms.AttachService;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.service.SystemService;

import tool.EmailTool;
import tool.ExportExcel;
import tool.ImageFileTools;
import tool.PDFTool;

/**   
 * 选择服务控制器
 */
@Controller
@RequestMapping("/selectService")
public class SelectServiceController extends BaseController {
	 
	private static final Logger logger = Logger.getLogger(SelectServiceController.class);
 
	@Autowired
	private SystemService systemService; 
	@Autowired
	private AttachService attachService;

	 
	@RequestMapping(params = "goSelect")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("demo/selectService");
	}  

	@RequestMapping(params = "goMyForm")
	public ModelAndView goMyForm(HttpServletRequest req) {		 
		return new ModelAndView("demo/myApplyList");
	}
	
	
	@RequestMapping(params = "goPage3")
	public ModelAndView goPage3(HttpServletRequest req) {
		String id = req.getParameter("id");
		if(id != null){
			ApplyForm apply = this.systemService.getEntity(ApplyForm.class, id);
			req.setAttribute("apply", apply);
		}
		return new ModelAndView("demo/page3");
	}
	
	@RequestMapping(params = "goPage6")
	public ModelAndView goPage6(HttpServletRequest req) {
		String id = req.getParameter("id");
		ApplyForm apply = this.systemService.getEntity(ApplyForm.class, id);
		req.setAttribute("apply", apply);
		return new ModelAndView("demo/page6");
	}
	
	@RequestMapping(params = "goChangePage")
	public ModelAndView goChangePage(HttpServletRequest req) {
		String id = req.getParameter("id");
		ApplyForm apply = this.systemService.getEntity(ApplyForm.class, id);
		req.setAttribute("apply", apply);
		
		if(!ApplyState.Changed.equals(apply.getState())){
			return new ModelAndView("demo/linksError");
		}else{
			
			if(!apply.getApplyUser().getId().equals(ResourceUtil.getSessionUserName().getId())){
				req.setAttribute("msg", "当前登录用户非此表单申请人，您无权查看！");
				return new ModelAndView("demo/linksError");
			}else{
				return new ModelAndView("demo/changePage");
			}
		} 
	}
	
	@RequestMapping(params = "goSign")
	public ModelAndView goSign(HttpServletRequest req) {
		String id = req.getParameter("id");
		ApplyForm apply = this.systemService.getEntity(ApplyForm.class, id);
		req.setAttribute("apply", apply);
		return new ModelAndView("demo/sign");
	}
	
	@RequestMapping(params = "goFinalPage")
	public ModelAndView goFinalPage(HttpServletRequest req) {
		String id = req.getParameter("id");
		ApplyForm apply = this.systemService.getEntity(ApplyForm.class, id);
		req.setAttribute("apply", apply);
		return new ModelAndView("demo/finalPage");
	}
	
	@RequestMapping(params = "goUploadSignFile")
	public ModelAndView goUploadSignFile(HttpServletRequest req) {
		String id = req.getParameter("id");
		ApplyForm apply = this.systemService.getEntity(ApplyForm.class, id);
		req.setAttribute("apply", apply);
		return new ModelAndView("demo/uploadSignFile");
	}
	
	
	
	@RequestMapping(params = "doAddApply")
	@ResponseBody
	public AjaxJson doAdd(ApplyForm apply, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String message = "添加成功";
		try{
			if(StringUtil.isEmpty(apply.getId())){
				apply.setId(null);
				apply.setApplyDate(new Date());
				apply.setServieType(ServiceType.BASQ);
				apply.setApplyUser(ResourceUtil.getSessionUserName());
				apply.setState(ApplyState.Submit);
				systemService.save(apply);
				
				EmailTool.sendAuditMsg(apply, request.getServerName(), 
						URLEncoder.encode("selectService.do?goPage4&id="+apply.getId(), "UTF-8"));
				
			}else{
				ApplyForm target = this.systemService.getEntity(ApplyForm.class, apply.getId());
				target.setBalance(apply.getBalance());
				target.setSellAmount(apply.getSellAmount());
				target.setSellAmountTax(apply.getSellAmountTax());
				target.setSpendAmount(apply.getSpendAmount());
				target.setSpendAmountTax(apply.getSpendAmountTax());
				systemService.save(target);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	
	@RequestMapping(params = "saveApplyChange")
	@ResponseBody
	public AjaxJson saveApplyChange(ApplyForm apply, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String message = "修改成功";
		try{			 
			ApplyForm target = this.systemService.getEntity(ApplyForm.class, apply.getId());
			target.setBalanceChange(apply.getBalance());
			target.setSellAmountChange(apply.getSellAmount());
			target.setSellAmountTaxChange(apply.getSellAmountTax());
			target.setSpendAmountChange(apply.getSpendAmount());
			target.setSpendAmountTaxChange(apply.getSpendAmountTax());
			target.setState(ApplyState.Changed);
			systemService.save(target);
			
			EmailTool.sendDataChangeMsg(target, request.getServerName(), 
					URLEncoder.encode("selectService.do?goChangePage&id="+target.getId(), "UTF-8"));
		}catch(Exception e){
			e.printStackTrace();
			message = "修改失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	
	@RequestMapping(params="submit")
	@ResponseBody
	public AjaxJson doSubmit(String id){
		ApplyForm form = this.systemService.getEntity(ApplyForm.class, id);
		form.setState(ApplyState.Submit);
		this.systemService.saveOrUpdate(form);
		return AjaxJson.getSuccessResult("提交成功！");
	}
	
	@RequestMapping(params="acceptChange")
	@ResponseBody
	public AjaxJson acceptChange(String id) throws Exception{
		ApplyForm form = this.systemService.getEntity(ApplyForm.class, id);
		
		form.setSellAmount(form.getSellAmountChange());
		form.setSellAmountTax(form.getSellAmountTaxChange());
		form.setSpendAmount(form.getSpendAmountChange());
		form.setSpendAmountTax(form.getSpendAmountTaxChange());
		form.setBalance(form.getSellAmountChange().subtract(form.getSpendAmountChange()));
		form.setState(ApplyState.Sign);
		this.systemService.saveOrUpdate(form);
		
		//生成临时excel和pdf，并且发送邮箱
		sendFilesToEmail(form);
		
		return AjaxJson.getSuccessResult("提交成功！");
	}
	
	
	
	private void sendFilesToEmail(final ApplyForm form) {
		Thread t = new Thread(
				new Runnable() {
					
					@Override
					public void run() {
						try{
							File pdffile = PDFTool.generateToFile(form,form.getApplyUser().getRealName()+"的报税单");
							ExportExcel exportExcel = new ExportExcel();
							File excelfile = exportExcel.exportExcelToTempFile(form,form.getApplyUser().getRealName()+"的报税单");
							File[] files = new File[]{pdffile,excelfile};
							EmailTool.sendFiles("您已经接受了报税申请的修改内容，具体内容请看附件","您已经接受了报税申请的修改内容，具体内容请看附件",files);
						}catch(Exception e){
							e.printStackTrace();
						}
					}
				});
		t.start();
	}

	@RequestMapping(params="finishApply",method=RequestMethod.POST)
	@ResponseBody
	public AjaxJson finishApply(String id,String img) throws IOException{
		//首先保存签名图片
		String[] imgProps = img.split(",");
		String imgData = imgProps[1];
		byte[] byteData = Base64.decode(imgData);
		File imgFile = ImageFileTools.saveFileFromByteArray("attach",byteData);
		Attach attach = new Attach();
		attach.setOrigFileName("签名图片.png");
		attach.setFileType("");
		attach.setOwnerId(id);
		attach.setCreateDate(new Date());
		attach.setFileName("attach"+"/"+imgFile.getName());
		long attachId = (Long) systemService.save(attach); 
		
		ApplyForm form = this.systemService.getEntity(ApplyForm.class, id);
		form.setState(ApplyState.FINISH);
		form.setSignAttachId(attachId);
		this.systemService.saveOrUpdate(form);
		return AjaxJson.getSuccessResult("提交成功！");
	}
	
	

	@RequestMapping(params="redirectPass",method=RequestMethod.POST)
	@ResponseBody
	public AjaxJson redirectPass(String id){
		ApplyForm form = this.systemService.getEntity(ApplyForm.class, id);
		form.setState(ApplyState.Sign);
		this.systemService.saveOrUpdate(form);
		return AjaxJson.getSuccessResult("提交成功！");
	}
	
	
	
	@RequestMapping(params="accept")
	@ResponseBody
	public AjaxJson accept(String id){
		ApplyForm form = this.systemService.getEntity(ApplyForm.class, id);
		form.setState(ApplyState.Sign);
		this.systemService.saveOrUpdate(form);
		return AjaxJson.getSuccessResult("提交成功！");
	}
	
	@RequestMapping(params="doSign")
	@ResponseBody
	public AjaxJson doSign(String id){
		ApplyForm form = this.systemService.getEntity(ApplyForm.class, id);
		form.setState(ApplyState.FINISH);
		this.systemService.saveOrUpdate(form);
		return AjaxJson.getSuccessResult("提交成功！");
	}
	
	
	
	@RequestMapping(params = "goPage4")
	public ModelAndView goPage4(HttpServletRequest req,String id) {
		ApplyForm form = this.systemService.getEntity(ApplyForm.class, id);
		req.setAttribute("apply", form);
		
		if(!ApplyState.Submit.equals(form.getState())){
			return new ModelAndView("demo/linksError");
		}else{
			return new ModelAndView("demo/page4");
		} 
	}
	  
	
	@RequestMapping(params = "myDatagrid")
	public void myDatagrid(ApplyForm dictTest,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ApplyForm.class, dataGrid);
		cq.addOrder("applyDate", SortDirection.desc);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, dictTest, request.getParameterMap());
		try{
			//自定义追加查询条件
			cq.eq("applyUser", ResourceUtil.getSessionUserName());
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.systemService.getDataGridReturn(cq, true); 
		
		TagUtil.datagrid(response, dataGrid);
	}
	
	@RequestMapping(params = "goAuditList")
	public ModelAndView goAuditList(HttpServletRequest req) {		 
		return new ModelAndView("demo/auditApplyList");
	}	
	@RequestMapping(params = "auditDatagrid")
	public void auditDatagrid(ApplyForm dictTest,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ApplyForm.class, dataGrid);
		cq.addOrder("applyDate", SortDirection.desc);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, dictTest, request.getParameterMap());
		try{
			//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.systemService.getDataGridReturn(cq, true); 
		
		TagUtil.datagrid(response, dataGrid);
	}
	
	@RequestMapping(params="exportExcel")
	public void exportExcel(String id,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		ApplyForm form = this.systemService.getEntity(ApplyForm.class, id);
		ExportExcel excel = new ExportExcel();
		
		//获取签名图片
		Attach attach = systemService.getEntity(Attach.class, form.getSignAttachId());
		File file = ImageFileTools.findImgFile(attach.getFileName());
		FileInputStream fis = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		if (file != null) { 
				byte[] buffer = new byte[1024];
				fis = new FileInputStream(file); 
				int count = fis.read(buffer, 0, buffer.length);
				while (count > 0) {
					baos.write(buffer, 0, count); 
					count = fis.read(buffer, 0, buffer.length);
				} 
		}

		String filename =  form.getApplyUser().getRealName()+"的报账单.xls";
		if (req.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {  
		    filename = URLEncoder.encode(filename, "UTF-8");  
		} else {  
		    filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");  
		}  
		
		resp.setHeader("content-disposition", "attachment;filename=" + filename);
		form.setAttachData(baos.toByteArray());
		excel.exportExcel(form, resp.getOutputStream());
	}

	
	
	@RequestMapping(params="exportPdf")
	public void exportPdf(String id,HttpServletRequest req,HttpServletResponse resp) throws IOException, DocumentException{
		ApplyForm form = this.systemService.getEntity(ApplyForm.class, id);
		
		//获取签名图片
		Attach attach = systemService.getEntity(Attach.class, form.getSignAttachId());
		File file = ImageFileTools.findImgFile(attach.getFileName());
		FileInputStream fis = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		if (file != null) { 
				byte[] buffer = new byte[1024];
				fis = new FileInputStream(file); 
				int count = fis.read(buffer, 0, buffer.length);
				while (count > 0) {
					baos.write(buffer, 0, count); 
					count = fis.read(buffer, 0, buffer.length);
				} 
		}

		String filename =  form.getApplyUser().getRealName()+"的报账单.pdf";
		if (req.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {  
		    filename = URLEncoder.encode(filename, "UTF-8");  
		} else {  
		    filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");  
		}  
		
		resp.setHeader("content-disposition", "attachment;filename=" + filename);
		form.setAttachData(baos.toByteArray());
		PDFTool.generate(resp.getOutputStream(), form);
	}
	
}
